<template>
    <div class="college-info">
        <h3 align="center">住宿信息</h3>
        <!-- 第一行卡片 -->
        <el-row justify="center">
            <el-col :span="16">
                <el-card shadow="hover" style="height: 40px">
                    <div class="head-info">
                        <span>
                            我住在
                            <span class="blue">{{ building }} 号楼 {{ room }}</span>
                            ，寝室考核获奖
                            <span class="lightblue">{{ rewardCount }}</span>
                            次,警告
                            <span class="red">{{ warningCount }}</span>
                            次
                        </span>
                    </div>
                </el-card>
            </el-col>
        </el-row>
        <!-- 第二行卡片 -->
        <el-row justify="center">
            <el-col :span="8">
                <el-card shadow="hover" style="height: 120px">
                    <img src="@/assets/badge.png" class="image" />
                    <el-statistic
                        title="获奖"
                        :value="rewardCount"
                        suffix="次"
                        class="demo-class"
                        :value-style="{ color: '#5B9DED' }"
                    />
                </el-card>
            </el-col>
            <el-col :span="8">
                <el-card shadow="hover" style="height: 120px">
                    <div class="img-box">
                        <img src="@/assets/warn.png" class="image" />
                    </div>
                    <el-statistic
                        title="警告"
                        :value="warningCount"
                        suffix="次"
                        class="demo-class"
                        :value-style="{ color: '#DB122B' }"
                    />
                </el-card>
            </el-col>
        </el-row>
        <el-row justify="center">
            <el-col :span="16">
                <el-card shadow="hover">
                    <div class="title">寝室考核荣誉称号与获奖情况</div>
                    <el-table
                        :data="dormTableData"
                        ref="table"
                        :header-cell-style="{ textAlign: 'center' }"
                        :cell-style="{ textAlign: 'center' }"
                        height="450"
                        empty-text="暂无数据"
                        :loading="isDormLoading"
                        :default-sort="{ prop: 'date', order: 'descending' }"
                    >
                        <el-table-column prop="date" label="考核时间" sortable />
                        <el-table-column prop="type" label="类型" sortable>
                            <template #default="{ row }">
                                <el-tag v-if="row.type === '获奖'" type="success">获奖</el-tag>
                                <el-tag v-else-if="row.type === '警告'" type="warning">警告</el-tag>
                                <el-tag v-else>{{ row.type }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="detail" label="说明" />
                    </el-table>
                </el-card>
            </el-col>
        </el-row>

        <h3 class="title">室友信息</h3>
        <el-row justify="center">
            <el-col :span="16">
                <el-card shadow="hover">
                    <el-carousel :interval="4000" type="card" height="300px" width="70px">
                        <el-carousel-item v-for="(dormmate, index) in dormmates" :key="index" height="200px">
                            <div class="dormmate-info" @click="goToDormmate(dormmate.stuId)">
                                <img :src="dormmate.photoUrl" class="avatar" />
                                <div class="info-item">{{ dormmate.name }}</div>
                                <div class="info-item">{{ dormmate.cls }}</div>
                                <div class="info-item">{{ dormmate.ancestry }}</div>
                            </div>
                        </el-carousel-item>
                    </el-carousel>
                </el-card>
            </el-col>
        </el-row>

        <h3 align="center">归寝信息</h3>
        <!-- 第一行卡片 -->
        <el-row justify="center">
            <el-col :span="5" class="table-col">
                <el-card shadow="hover" style="height: 100px">
                    <img src="@/assets/clock.png" class="image1" />
                    <el-statistic
                        title="本学期平均归寝时间:"
                        :value="average"
                        class="demo-class1"
                        :value-style="{ color: '#175797' }"
                    />
                </el-card>
            </el-col>
            <el-col :span="5">
                <el-card shadow="hover" style="height: 100px">
                    <img src="@/assets/bell.png" class="image1" />
                    <el-statistic
                        title="本学期晚归:"
                        :value="lateCount"
                        suffix="次"
                        class="demo-class1"
                        :value-style="{ color: '#F59B26' }"
                    />
                </el-card>
            </el-col>
            <el-col :span="5" class="table-col-1">
                <el-card shadow="hover" style="height: 100px">
                    <img src="@/assets/lightning.png" class="image1" />
                    <el-statistic
                        title="本学期未归:"
                        :value="absentCount"
                        suffix="次"
                        class="demo-class1"
                        :value-style="{ color: '#D81E06' }"
                    />
                </el-card>
            </el-col>
        </el-row>
        <!-- 第二行卡片 -->
        <el-row justify="center">
            <el-col :span="8">
                <el-card shadow="hover">
                    <div class="title">本学期每天归寝时间</div>
                    <div ref="sleepChart" class="dailySleepChart"></div>
                </el-card>
            </el-col>
            <el-col :span="8">
                <el-card shadow="hover">
                    <div class="title">入学起每学期平均归寝时间</div>
                    <div ref="avgSleepChart" class="averageSleepChart"></div>
                </el-card>
            </el-col>
        </el-row>
        <!-- 第二行卡片 -->
        <el-row justify="center">
            <el-col :span="16">
                <el-card shadow="hover">
                    <div class="title">晚归和未归详情</div>
                    <el-table
                        :data="sleepTableData"
                        ref="table"
                        :header-cell-style="{ textAlign: 'center' }"
                        :cell-style="{ textAlign: 'center' }"
                        height="450"
                        empty-text="暂无数据"
                        :loading="isSleepLoading"
                        :default-sort="{ prop: 'date', order: 'descending' }"
                    >
                        <el-table-column prop="date" label="日期" sortable />
                        <el-table-column prop="type" label="类型" sortable>
                            <template #default="{ row }">
                                <el-tag v-if="row.type === '未归'" type="danger">未归</el-tag>
                                <el-tag v-else-if="row.type === '晚归'" type="warning">晚归</el-tag>
                                <el-tag v-else>{{ row.type }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="time" label="归寝时间" sortable />
                    </el-table>
                </el-card>
            </el-col>
        </el-row>
    </div>
</template>

<script></script>
<script setup>
import { reactive, ref, onMounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import { useRouter } from 'vue-router'
import api from '@/api/student'

const sleepChart = ref(null)
const avgSleepChart = ref(null)

const props = defineProps({
    college: Object,
})

const dormTableData = reactive([])
const isDormLoading = ref(false)
const sleepTableData = reactive([])
const isSleepLoading = ref(false)

const rewardCount = ref(0)
const warningCount = ref(0)
const building = ref('')
const room = ref('')

const dormmates = ref([])
const isDormmatesLoading = ref(false)

const sleepTimes = reactive([])
const averages = reactive([])

const average = ref('')
const lateCount = ref(0)
const absentCount = ref(0)

const BASE_DATE = '2023-01-01 '

const getDormInfo = async () => {
    if (props.college && props.college.id) {
        isDormLoading.value = true
        try {
            const response = await api.getDorm(props.college.id)
            dormTableData.splice(0)
            dormTableData.push(...response.data.appraisals)

            building.value = response.data.building
            room.value = response.data.room

            rewardCount.value = 0
            warningCount.value = 0

            response.data.appraisals.forEach((appraisal) => {
                if (appraisal.type === '获奖') {
                    rewardCount.value++
                } else if (appraisal.type === '警告') {
                    warningCount.value++
                }
            })
            console.log(response.data.appraisals)
        } catch (error) {
            console.error(error)
        } finally {
            isDormLoading.value = false
        }
    }
}

const initSleepChart = () => {
    console.log('sleepTimes.value', sleepTimes.value)
    if (!sleepChart.value || !sleepTimes.value || sleepTimes.value.length === 0) return

    const times = sleepTimes.value.map((item) => BASE_DATE + item.time)
    const date = sleepTimes.value.map((item) => item.date)

    nextTick(() => {
        const mySleepChart = echarts.init(sleepChart.value)
        let dataZoomEnd = date.length > 25 ? 30 : 100

        const option = {
            tooltip: {
                trigger: 'axis',
                formatter: function (params) {
                    const date = params[0].axisValue
                    const time = params[0].data

                    return `日期：${date}<br>时间：${time.split(' ')[1]}`
                },
            },
            dataZoom: [
                {
                    type: 'slider',
                    show: dataZoomEnd !== 100,
                    realtime: true,
                    start: 0,
                    end: dataZoomEnd,
                },
                {
                    type: 'inside',
                    realtime: true,
                    start: 0,
                    end: dataZoomEnd,
                },
            ],
            xAxis: {
                type: 'category',
                axisLabel: {
                    interval: 0,
                    rotate: 45,
                },
                name: '日期',
                data: date.map((item) => parseInt(item.split('-')[1]) + '.' + parseInt(item.split('-')[2])),
            },
            yAxis: [
                {
                    type: 'time',
                    name: '时间',
                    min: BASE_DATE + '18:00',
                    max: BASE_DATE + '24:00',
                    // interval: 1,
                    // axisLabel: {
                    //     formatter: '{value}',
                    // },
                },
            ],
            series: [
                {
                    type: 'line',
                    data: times,
                },
            ],
        }

        mySleepChart.setOption(option)
    })
}

const initAvgSleepChart = () => {
    if (!avgSleepChart.value || !averages.value || averages.value.length === 0) return

    nextTick(() => {
        const myAvgSleepChart = echarts.init(avgSleepChart.value)

        const semesters = averages.value.map((item) => item.semester)
        const selfTimes = averages.value.map((item) => item.self)
        const otherTimes = averages.value.map((item) => item.other)

        const option = {
            tooltip: {
                formatter: function (params) {
                    const semester = params[0].name
                    const selfTime = params[0].value
                    const otherTime = params[1].value

                    return `${semester} <br/> 平均归寝时间：${selfTime.split(' ')[1]} <br/>
                                全校平均归寝时间：${otherTime.split(' ')[1]}`
                },
                trigger: 'axis',
                // axisPointer: {
                //     type: 'cross',
                //     crossStyle: {
                //         color: '#999',
                //     },
                // },
            },
            xAxis: [
                {
                    type: 'category',
                    data: semesters,
                    axisLabel: {
                        interval: 0,
                        rotate: 45,
                    },
                    interval: 1,
                    name: '学期',
                    axisPointer: {
                        type: 'shadow',
                    },
                },
            ],
            yAxis: [
                {
                    type: 'time',
                    name: '时间',
                    min: `${BASE_DATE}20:00`,
                    max: `${BASE_DATE}24:00`,
                    // interval: 1,
                    // axisLabel: {
                    //     formatter: '{value}',
                    // },
                },
            ],
            series: [
                {
                    name: 'self',
                    type: 'bar',
                    data: selfTimes.map((time) => BASE_DATE + time),
                },
                {
                    name: 'other',
                    type: 'line',
                    data: otherTimes.map((time) => BASE_DATE + time),
                },
            ],
        }

        myAvgSleepChart.setOption(option)
    })
}

const getSleepStats = async () => {
    if (props.college && props.college.id) {
        isSleepLoading.value = true
        try {
            const response = await api.getStatistic(props.college.id)
            sleepTableData.splice(0)
            sleepTableData.push(...response.data.records)

            average.value = response.data.average

            sleepTimes.value = response.data.times
            averages.value = response.data.averages

            for (const record of sleepTableData) {
                if (record.type === '晚归') {
                    lateCount.value++
                } else if (record.type === '未归') {
                    absentCount.value++
                }
            }

            console.log(response.data.records)
            console.log('response.data.times' + response.data.times)
            console.log(response.data.averages)
        } catch (error) {
            console.error(error)
        } finally {
            isSleepLoading.value = false
        }
    }
}

const getDormmates = async () => {
    try {
        isDormmatesLoading.value = true
        const response = await api.getDormmates(props.college.id)
        dormmates.value = response.data

        console.log(dormmates.value)
    } catch (error) {
        console.error(error)
    } finally {
        isDormmatesLoading.value = false
    }
}

const router = useRouter()
const goToDormmate = async (stuId) => {
    try {
        await router.push({
            name: 'StudentInfoPage',
            params: {
                id: stuId,
            },
        })
        location.reload()
    } catch (error) {
        console.error(error)
    }
}

onMounted(async () => {
    if (props.college && props.college.id) {
        await fetchData()
    }
})

const fetchData = async () => {
    await getDormInfo()
    await getSleepStats()
    await getDormmates()
    if (sleepTimes.value.length > 0 && averages.value.length > 0) {
        initSleepChart()
        initAvgSleepChart()
    }
}

watch(
    () => props.college.id,
    async (newId, oldId) => {
        if (newId !== oldId) {
            await fetchData()
        }
    }
)
</script>

<style scoped>
.college-info {
    display: flex;
    flex-direction: column;
    align-items: center;
    background-color: #e8e8e8;
}

.el-row {
    width: 100%;
}

.el-col {
    flex: 1;
    box-sizing: border-box;
}

.el-card {
    width: 100%;
    margin: 0 0 10px 0;
}

.head-info {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 50px;
    position: relative;
    transform: translateY(-50%);
    font-size: 18px;
    text-align: center;
}

.blue {
    color: #175797;
}

.lightblue {
    color: #589ced;
}

.red {
    color: red;
}

.image {
    position: relative;
    top: 10px;
    left: 130px;
    width: 60px;
    display: block;
}
.title {
    text-align: center;
}

.dormmate-info {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    margin: 40px 152px 0;
}

.avatar {
    width: 120px;
    height: 120px;
    margin-top: -75px;
    border-radius: 50%;
    margin-bottom: 10px;
}

.info-item {
    font-size: 18px;
    margin: 5px 0;
    width: 100%;
    text-align: center;
}

.image1 {
    position: relative;
    left: 20px;
    width: 60px;
    display: block;
}

.demo-class {
    position: relative;
    top: -47px;
    left: 230px;
    width: 90px;
    /* border: solid red 1px; */
}

.demo-class1 {
    position: relative;
    top: -55px;
    left: 120px;
    width: 120px;
    /* border: solid red 1px; */
}

.title {
    font-size: 18px;
    font-weight: bold;
    color: #909399;
    text-align: center;
    margin: 0 0 25px 0;
}

/* 走马灯 */
.el-carousel__item h3 {
    color: #475669;
    opacity: 0.75;
    line-height: 200px;
    margin: 0;
}

.el-carousel__item:nth-child(2n) {
    background-color: #d6e4f3;
}

.el-carousel__item:nth-child(2n + 1) {
    background-color: #d6e4f3;
}

.table-col {
    margin: 0 30px 0 0;
}

.table-col-1 {
    margin: 0 0 0 30px;
}

.dailySleepChart {
    margin: 0 auto;
    height: 398px;
    width: 390px;
}

.averageSleepChart {
    margin: 0 auto;
    height: 398px;
    width: 390px;
}
</style>
